package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.db.User;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Comment;
import com.tanhua.mongo.FollowUser;
import com.tanhua.mongo.Video;
import com.tanhua.template.OssTemplate;
import com.tanhua.vo.PageBeanVo;
import com.tanhua.vo.UserHolder;
import com.tanhua.vo.VideoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.protocol.rest.ViolationReport;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
public class VideoService {
    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FdfsWebServer webServer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Cacheable(value = "video")  //pageBean 放入redis中的资源必须实现序列化
    public PageBeanVo findVideoVoByPage(Integer pageNum, Integer pageSize) {
        System.out.println("我是redis，我执行了");
        PageBeanVo pageBeanVo = videoApi.findByPage(pageNum, pageSize);
        List<Video> items = (List<Video>) pageBeanVo.getItems();
        ArrayList<VideoVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Video video : items) {
                VideoVo videoVo = new VideoVo();
                UserInfo userInfo = userInfoApi.findByUserId(video.getUserId());

                BeanUtils.copyProperties(userInfo, videoVo);
                videoVo.setUserId(userInfo.getId());

                BeanUtils.copyProperties(video, videoVo);
                videoVo.setSignature(video.getText());
                videoVo.setCover(video.getPicUrl());
                videoVo.setVideoUrl(video.getVideoUrl());
                // 下去如果点赞 这里要从redis中获取
                videoVo.setHasLiked(0);
                if (stringRedisTemplate.hasKey(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), video.getUserId()))) {
                    videoVo.setHasFocus(1);
                } else {
                    videoVo.setHasFocus(0);
                }
                voList.add(videoVo);
            }
            pageBeanVo.setItems(voList);
        }
        return pageBeanVo;
    }

    @CacheEvict(value = "video", allEntries = true)
    public ResponseEntity saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //封面地址（上传到阿里云）
        String fmUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //视频地址（保存到fastdfs)
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        Video video = new Video();
        video.setUserId(UserHolder.getUser().getId());
        video.setPicUrl(fmUrl);
        video.setVideoUrl(videoUrl);
        video.setText("深夜蹦迪");
        //插入数据
        videoApi.save(video);
        System.out.println(video);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity focus(Long followUserId) {
        FollowUser followUser = new FollowUser();
        followUser.setCreated(System.currentTimeMillis());
        followUser.setUserId(UserHolder.getUser().getId());
        followUser.setFollowUserId(followUserId);
        videoApi.saveFollowUser(followUser);
        //设置redis
        stringRedisTemplate.opsForValue().set(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), followUserId), "1");
        return ResponseEntity.ok(null);
    }

    public ResponseEntity unFocus(Long followUserId) {
        videoApi.removeFollowUser(UserHolder.getUser().getId(), followUserId);
        stringRedisTemplate.delete(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), followUserId));

        return ResponseEntity.ok(null);

    }

    //推荐小视频
    public void toBigDate2(int type, String videoId) {
        Map map = new HashMap<>();
        map.put("type", type);
        map.put("userId", UserHolder.getUser().getId());

        //根据publishId获取publish对象
        Video video = videoApi.findById(videoId);
        map.put("vid", video.getVid());
        rocketMQTemplate.convertAndSend("tanhua-bigdata2", map);
    }
}
